package com.zking.ssm.controller;

import com.zking.ssm.biz.ClazzBiz;
import com.zking.ssm.model.Clazz;
import com.zking.ssm.model.dto.ClazzDto;
import com.zking.ssm.util.PageBean;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author小李飞刀
 * @site www.javaxl.com
 * @company xxx公司
 * @create  2022-08-17 15:23
 */
@Controller
@RequestMapping("/clz")
public class ClazzController {
    @Autowired
    private ClazzBiz clazzBiz;
//    list->clzList
//    toList->重定向list->"redirect:/clz/list"
//    toEdit->跳转到编辑界面->clzEdit
//    Clazz : 以前是通过模型驱动接口封装，现在是直接在方法中接受参数即可
    @RequestMapping("/list")
    public String list(Clazz clazz, HttpServletRequest request){
        System.out.println("我添加了 新的代码,终于不重启了....");
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<Clazz> lst = this.clazzBiz.listPager(clazz, pageBean);
        request.setAttribute("lst",lst);
        request.setAttribute("pageBean",pageBean);
        return "clzList";
    }

    @RequestMapping("/toEdit")
    public String toEdit(Clazz clazz, HttpServletRequest request){
        Integer cid = clazz.getCid();
//        传递的id代表了修改，没传代表新增
        if(cid != null){
            List<Clazz> lst = this.clazzBiz.listPager(clazz, null);
            request.setAttribute("b",lst.get(0));
        }
        return "clzEdit";
    }

    @RequestMapping("/add")
    public String add(Clazz clazz){
        this.clazzBiz.insertSelective(clazz);
        return "redirect:/clz/list";
    }

    /**
     * @Valid 是与实体类中 的服务端校验 注解配合使用的
     * BindingResult 存放了所有违背 校验的错误信息
     * @param clazz
     * @param bindingResult
     * @return
     */
    @RequestMapping("/valiAdd")
    public String valiAdd(@Valid Clazz clazz, BindingResult bindingResult,HttpServletRequest request){
        if (bindingResult.hasErrors()){
            Map msg = new HashMap();
//            违背规则
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
//                cid : cid不能为空
                System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
//                msg.put(cid,cid不能为空);
                msg.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            request.setAttribute("msg",msg);
//            如果出现了错误，应该将提示语显示在 表单提交元素后方
            return "clzEdit";
        }else {
            this.clazzBiz.insertSelective(clazz);
        }
        
        return "redirect:/clz/list";
    }

    @RequestMapping("/edit")
    public String edit(Clazz clazz){
        this.clazzBiz.updateByPrimaryKeySelective(clazz);
        return "redirect:/clz/list";
    }

    @RequestMapping("/del")
    public String del(Clazz clazz){
        this.clazzBiz.deleteByPrimaryKey(clazz.getCid());
        return "redirect:/clz/list";
    }

//    文件上传
    @RequestMapping("/upload")
    public String upload(ClazzDto clazzDto){
        try {
            //        前台上传文件
            MultipartFile picFile = clazzDto.getPicFile();
//          实际应该配置到 resource.properties 中
            String diskPath = "E:/temp/T280/";// 图片的存放地址
//            http://localhost:8080/upload/mvc/0516.png
            String requestPath = "/upload/mvc/";// 数据库保存的地址，也是访问地址


//            拿到上传文件的名字
            String fileName = picFile.getOriginalFilename(); //0516.png
            FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(diskPath+fileName));

//            将图片上传之后，并且将图片地址更新到数据库中
            Clazz clazz = new Clazz();
            clazz.setCid(clazzDto.getCid());
            clazz.setPic(requestPath+fileName);
            this.clazzBiz.updateByPrimaryKeySelective(clazz);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "redirect:/clz/list";
    }

    @RequestMapping("/download")
    public ResponseEntity download(ClazzDto clazzDto){
        try {
//            1.点击下载传递文件的ID，通过文件的ID查询出文件的路径
            Clazz clazz = this.clazzBiz.selectByPrimaryKey(clazzDto.getCid());
            String pic = clazz.getPic();// /upload/mvc/0314.png
            //          实际应该配置到 resource.properties 中
            String diskPath = "E:/temp/T280/";// 图片的存放地址
//            http://localhost:8080/upload/mvc/0516.png
            String requestPath = "/upload/mvc/";// 数据库保存的地址，也是访问地址

//            2.通过文件的请求地址，转换成文件存放的硬盘地址
            String realPath = pic.replace(requestPath,diskPath);//  E:/temp/T280/0314.png
            String fileName = realPath.substring(realPath.lastIndexOf("/")+1);

//            3.将硬盘中文件下载下来->固定代码
            //下载关键代码
            File file=new File(realPath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType：具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
